package com.cdvtc.news.web;

import com.cdvtc.news.entity.*;
import com.cdvtc.news.service.CategoryService;
import com.cdvtc.news.service.CommentService;
import com.cdvtc.news.service.NewsService;
import com.cdvtc.news.service.TagService;
import com.cdvtc.news.util.CommentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Set;

@Controller
public class IndexController {
    @Autowired
    private NewsService newsService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private TagService tagService;

    @Autowired
    private CommentService commentService;

    @RequestMapping("/")
    public String home(Model model, HttpSession session, @RequestParam(value = "category", required = false) Integer category, @RequestParam(value = "tag", required = false) Integer tag) {
        List<Category> categories = categoryService.getAllCategories();
        session.setAttribute("categories",categories);

        List<Tag> tags = tagService.getAllTags();
        model.addAttribute("tags", tags);

        List<News> hotNews = newsService.getHotNews();
        session.setAttribute("hotNews", hotNews);

        List<News> newsList = newsService.getNews(category, tag);
        model.addAttribute("newsList", newsList);
        return "index";
    }

    @RequestMapping("/news/{newsId}")
    public String news(@PathVariable Integer newsId, Model model) {

        News news = newsService.getNewsById(newsId);
        model.addAttribute("news", news);

        List<Comment> comments =  commentService.getCommentsByNewsId(newsId);
        model.addAttribute("comments", comments);
        model.addAttribute("commentMap", CommentUtil.toMap(comments)); //保存评论Map，解决jsp:param不能传对象的问题（改为只传Id）


        Set<Tag> tagSet = tagService.getTagsByNewsId(newsId);
        model.addAttribute("tagSet", tagSet);

        List<News> recommendedNews = newsService.getRecommendedNews(newsId);
        model.addAttribute("recommendedNews", recommendedNews);

        // 更新点击计数
        newsService.updateClickCount(newsId);

        return "news";
    }


    /**
     * 评论
     * @return
     */
    @RequestMapping(value = "/comment/{newsId}", method = RequestMethod.POST)
    public String comment(@PathVariable Integer newsId, String content, @RequestParam(value = "replyForId", required = false) Integer replyForId, HttpServletRequest request, HttpSession session){
        User user = (User)session.getAttribute("user"); // 获取当前登陆用户

        Comment comment = new Comment();
        comment.setContent(content);
        News news = new News();
        news.setId(newsId);
        comment.setNews(news);
        comment.setCreator(user);
        comment.setIpAddress(request.getRemoteAddr());  //获取用户IP地址
        if(replyForId != null){
            Comment replyFor = new Comment();
            replyFor.setId(Long.valueOf(replyForId));
            comment.setReplyFor(replyFor);
        }

        commentService.addComment(comment);
        return "redirect:/news/"+newsId;  //页面跳转回当前新闻页
    }

    /**
     * 评论点赞（踩）
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/commentLike/{id}/{operate}", method = RequestMethod.POST)
    public Integer commentLike(@PathVariable Long id, @PathVariable String operate) {
        int resultNum = -1;
        if("like".equals(operate) || "unlike".equals(operate)) {  //点赞或取消点赞
            resultNum = commentService.updateLikeNum(id, "like".equals(operate));
        } else if("dislike".equals(operate) || "undislike".equals(operate)) { //踩或取消踩
            resultNum = commentService.updateDislikeNum(id, "dislike".equals(operate));
        }

        return resultNum;
    }

}
